
class Room {
  constructor(rooms) {
    this.id = rooms.length;
  }
}

const rooms = [];

module.exports = server => ({
  getRooms: () => rooms,
  createRoom: fileName => {
    const room = new Room(rooms);
    room.fileName = fileName;
    room.instance = server.of('/room/' + room.id);
    room.instance.on('connection', socket => {
      console.log(Date.now() + 'new viewer :  '.green + 'someone has connected'.yellow);
      socket.emit('newMessage', {
        username: 'admin',
        content: "u've been connected",
        timeStamp: Date.now()
      });
      socket.on('postMessage', data => {
        console.log(Date.now() + 'socket message :  '.green + data.content.yellow);
        room.instance.emit('newMessage', {
          username: data.username,
          content: data.content,
          timeStamp: Date.now()
        })
      });
      socket.on('newAction', obj => {
        room.instance.emit('newAction', {
          action: obj.action,
          time: obj.time,
          username: obj.username,
          content: `${obj.username} has emitted a ${obj.action} event`,
          timeStamp: Date.now()
        })
      });
      socket.on('disconnect', () => room.instance.clients((error, clients) => {
        if(error) throw error.stack;
        if(clients.length === 0) {
          rooms.splice(rooms.indexOf(room), 1)
        }
      }));
    });
    rooms.push(room);
    return room.id
  }
});


/**
 * Created by lz on 2017/6/9.
 */
